[#ftl]
[#include "MockupEditPage.ftl"/]
[#assign sourceTemplate]
[#include "../sourceTemplate.ftl"/]
[/#assign]

[@define "agile.MockupWorkspace" "TabContainer"][#--,agile._ContainerToolbar--]
	sourceTemplate:"${sourceTemplate?js_string}"
	,context:"${webAppHost}${context}"	
	,constructor:function(){
//		console.log("MockupWorkspace#######this.id",this.id);
//		this.id = registry.getUniqueId("MockupWorkspace");
//		console.log("MockupWorkspace@@@@@@@this.id",this.id);
		this.subscribe("agile.workspace.command",function(command){				
			if(this["actionOnCommand" + command]){
				this["actionOnCommand" + command]();
			}else{
				console.error("function 'actionOnCommand" + command +"' is not defined");
			}			
		});
		
		this.own(aspect.after(this,"startup",lang.hitch(this,"init1")));
		
//		this.subscribe("agile.sitemap.data",function(sitemapData){
//			console.log("received sitemapData:",sitemapData)
//		});
		
//		this.subscribe("agile.ready",lang.hitch(this,"init"));	
		
//		this._previewer = new dijit.Dialog({style:"display:none;width:99%;height:99%;background-color:white;overflow:hidden"});
//		this._previewer.placeAt(_window.body())
		this.historyPages = {};		
	}
	,createId:function(){
		return "p"+(new Date().getTime()) + "1234567890".substring(Math.floor(Math.random()*10));
	}
	,init1:function(){
		console.info("initializing workspace...");
		
		this.pages = [];
[#--		
//		if(window["ls"]["agile.workspace"]){
////			console.log('window["ls"]["agile.workspace"]=',window["ls"]["agile.workspace"]);						
//			if(window["ls"]["agile.workspace"].indexOf(";") != -1){		
//				var tabs = window["ls"]["agile.workspace"].split(";");
//				for(var i = 0; i < tabs.length; i++){
//					if(tabs[i]){
//						var page = null;
//						try{
//							page = json.parse(tabs[i],false);
//						}catch(e){
//							page = {title:tabs[i],store:tabs[i],id:this.createId()};
//						}
//						this.pages.push(page);
//					}
//				}					
//				window["ls"]["agile.workspace"] = agile.toJson({"pages":this.pages});
//			}
//			else{				
//				var workspace = json.parse(window["ls"]["agile.workspace"],false);			
//				if(!workspace.pages){
//					this.pages.push({"title":"Home","id":"home","store":this.createId()});
//					this.pages.push({"title":"SAMPLE","store":"sample"});
//					window["ls"]["agile.workspace"] = agile.toJson({"pages":this.pages});
//				}else{
//					this.pages = workspace.pages;	
//				}	
//			}
//		}else{
//			this.pages.push({"title":"sample","store":"sample"});
//			window["ls"]["agile.workspace"] = agile.toJson({"pages":this.pages});
//		}
--]		
		[#assign sample][#include "../sample.ftl"/][/#assign]
		window["ls"]["sample"] = "${sample?js_string}";
		
		if(window["ls"]["agile.sitemap"]){			
			//get pages from site map
			this.pages = array.filter(json.parse(window["ls"]["agile.sitemap"],false),function(page){return page.open;});			
		}else if(window["ls"]["agile.workspace"]){
			//convert existing pages to site map
			var workspace = json.parse(window["ls"]["agile.workspace"],false);	
			this.pages = workspace.pages;
			var homeExist = false;
			array.forEach(this.pages,function(page){
				page.parent = "home";				
				page.open = true;
				homeExist = (page.id == "home");
				if(!page.id){
					page.id = this.createId();
				}
			},this);	
			
			if(!homeExist){
				this.pages.push({"id":"home","title":"Home","open":true,"store":this.createId(),"closable":false});
				this.pages.reverse();
			}
			window["ls"]["agile.sitemap"] = json.stringify(this.pages);
		}else{
			this.pages.push({"id":"home","title":"Home","open":true,"store":this.createId(),"closable":false});
			window["ls"]["agile.sitemap"] = json.stringify(this.pages);
		}
		
//		topic.publish("agile.sitemap.ready");
		
		this.subscribe("agile.ready",function(obj){
			if(obj == "Application"){
				for(var i = 0; i < this.pages.length; i++){
					var page = this.createChild(this.pages[i]);
					this.historyPages[page.id] = page;			
					this.addComponent(page);
				}
//				this.resize();				
			}
		});
		
//		//display the selected page default
//		this.subscribe("agile.ready",function(){
//			var selectedPage = this.getSelectedChildren()[0];
//			this.onPageSelected(selectedPage);
//			//console.error(this.declaredClass,"agile.ready")
//			//topic.publish("agile.widget.selected",selectedPage);
//		});
//		
		
//		aspect.after(this,"resize",lang.hitch(this,function(){
//			array.forEach(this.getChildren(),function(page){
//				page.resize();
//			})
//		}));	
		
		style.set(this.domNode,"cursor","default");
[#--		
//		//call agile._ContainerToolbar.init() to initialize the toolbar
//		if(!this.readOnly){
//			this.init();
//		}
	
//		this.own(
//		aspect.after(this,"removeChild",lang.hitch(this,function(child){
//			child.selected = false;
//			if(window["ls"]){
////				window["ls"]["agile.workspace"] = window["ls"]["agile.workspace"].replace("{"+lang.replace('"title":"{title}","store":{store}',child)+"};","");
//				var pages = this.pages;
//				for(var i = pages.length - 1; i >= 0; i--){
//					if(pages[i].store == child.metadata("parameters.store")){
//						pages.splice(i,1);
//						break;
//					}
//				}
//				window["ls"]["agile.workspace"] = agile.toJson({"pages":pages});				
//			}
//		}),true)
//		
//		,aspect.after(this,"addChild",lang.hitch(this,function(child){
//			if(window["ls"]){
////				window["ls"]["agile.workspace"] += "{"+lang.replace('"title":"{title}","store":{store}',child)+"};";
//				var pages = this.pages;
//				pages.push({"title":child.metadata("parameters.title"),"store":child.metadata("parameters.store")});
//				window["ls"]["agile.workspace"] = agile.toJson({"pages":pages});
//			}
//			child._applicationReady = true;			
//			child.resize();
//		}),true)
//		);
--]			
//		this.subscribe(this.id+"-selectChild","onPageSelected");
		
		//keep the page in history in case of reopen without rendering again
		aspect.after(this,"removeChild",lang.hitch(this,function(page){			
			this.historyPages[page.id] = page;
		}),true);
		
		this.subscribe("agile.sitemap.changed",function(operation,item){
			//console.log("sitemap changed:",operation,item);
			if(operation == "add"){//a new page item has been added to the sitemap
				
			}else if(operation == "remove"){
				//an existing page item has been removed from sitemap, remove the page from workspace if it is open
				//topic.publish("agile.message.confirm",agile.i18n("msg_remove_confirm"),null,this,{ok:function(){
					//console.log("this.selectedChild=",this.selectedChild);				
					var child = array.filter(this.getChildren(),function(page){return page.id == item.id})[0];
					if(child){
						this.removeChild(child);
						agile.commit([{action:"delete",target:child}]);
						topic.publish("agile.widget.removed",child);
					}
				//},cancel:function(){}});
				
			}else if(operation == "open"){
				//open the page in workspace and make it as the selected page
				var child = array.filter(this.getChildren(),function(page){return page.id == item.id})[0];
				if(!child){//page does not exists in workspace					
					child = this.historyPages[item.id];//check whether the page was opened before
					if(!child){//create new page
						child = this.createChild(item);
						this.historyPages[item.id] = child;	
					}
					this.addComponent(child);
					agile.commit([{action:"add",target:child}]);					
				}		

				this.selectChild(child); 
				
			}else if(operation == "update"){
				var child = array.filter(this.getChildren(),function(page){return page.id == item.id})[0];
				if(child){
					child.metadata("parameters.title",item.title);
					child.set("title",item.title);
				}
			}
		});
	}
//	,init:function(){
//		
//	}
//	,createTitleEditor:function(child){
//		console.log("controlButton=",child.controlButton.containerNode);
//		var titleWidget = new InlineEditBox({width:"100px"},child.controlButton.containerNode);	
//		titleWidget.startup();
//		agile.stopInlineEditBox(titleWidget);
//		child.titleWidget = titleWidget;
//		child.titleWidget.set("disabled",!child.editable);
//		var parent = this;
//		child.beforeValue = child.get("title");
//		aspect.after(titleWidget,"onChange",lang.hitch(child,function(value){
//			if(value){				
//				var isValid = true;
//				var siblings = parent.getChildren();
//				for(var i = siblings.length - 1; i >= 0; i--){
//					if(siblings[i] != this && siblings[i].get("title") == value){
//						isValid = false;
//						break;
//					}
//				}
//				if(isValid){
//					if(window["ls"]){
//						//console.log("@@@@@@@@",window["ls"]["agile.workspace"],this.beforeValue,value);
//						window["ls"]["agile.workspace"] = window["ls"]["agile.workspace"].replace(this.beforeValue,value);
//						
//						//window["ls"][value] = window["ls"][this.beforeValue];
//					}
//					this.set("title",value);
//					this.beforeValue = value;
//					this.metadata("parameters.title",value);
//				}else{
//					topic.publish("agile.message","error",null,agile.i18n("msg_already_exists",[value]),null);
//					titleWidget.reset1("value",this.beforeValue);
//				}
//			}else{
//				titleWidget.reset1("value",this.beforeValue);
//			}
//		}),true);		
//	}
	,_getChildren:function(){
		return this.getChildren();
	}
	,addComponent:function(child,offset){
		this.addChild(child);
//		if(child.editable){
//			this.createTitleEditor(child);
//		}	
		child.parent = this;
	}
	,createChild:function(metadata){		
//		console.log("#####metadata",metadata);
		var page = new agile.MockupEditPage(
			lang.mixin({/*store:new Date().getTime(),title:"page"+ (new Date().getTime()),*/editable:true},metadata)
		);
//		if(metadata && metadata.store){
//			page.fetched = false;	
//		}else{
//			page.fetched = true;
//		}
//		page.metadata("parameters.editable",true);
//		page.editable = true;
		page.workspace = this;
		//page.parent = this;
//		page.metadata("anchor",{left:0,top:0});
[#--//moved to MockupEditPage		
//		page.watch("title",lang.hitch(page,function(name,old,value){
//			this.metadata("parameters.title",value);
//			var pages = this.workspace.pages; 
//			for(var i = 0; i < pages.length; i++){
//				if(pages[i].store == page.store){
//					pages[i].title = value;
//				}
//			}
//			if(window["ls"]){
//				window["ls"]["agile.workspace"] = agile.toJson({"pages":pages});				
//				//console.log('#############window["ls"]["agile.workspace"]=',agile.toJson({"pages":pages}));
//			}
//		}));
--]		
		return page;
	}
	,adviseTitle:function(child,title){
		var duplicated = false;
		for(var i = 0; i < this.pages.length; i++){
			if(this.pages[i].store != child.store && this.pages[i].title == title){
				duplicated = true;
			}
		}
		if(duplicated){			
			topic.publish("agile.message","error",null,agile.i18n("msg_already_exists",[title]),null);
		}else{			
			child.set("title",title);	
		}
	}
	,getSelectedChildren:function(){
		return array.filter(this.getChildren(),function(child){return child.selected});
	}
[#--	
//	,postInitToolbar:function(){	
//		style.set(this.addButton,"position","absolute");
//		style.set(this.removeButton,"position","absolute");
//		this.addButton.title = agile.i18n("add_btn_tooltip",["page"],true);
//		this.removeButton.title = agile.i18n("remove_btn_tooltip",["page"],true);
//	}
--]	
	,actionOnCommandNew:function(){		
		var child = this.createChild();	
		this.addChild(child);
		//this.createTitleEditor(child);
	}
	,actionOnCommandSave:function(){
		
	}
	,actionOnCommandOpen:function(){
		
	}
	,actionOnCommandPreview:function(){
		//TODO:preview on all pages
		var currentPage = this.selectedChildWidget;	
		var prototype =  currentPage.toHtml({cascade:true,indentCount:0,sourceType:"dojo"});
		var store = currentPage.get("store");
		window["ls"]["prototype"+store] = prototype;
		window["ls"]["preview"] = store;
		[#if applicationMode = "PROD"]
		window.open("/prototype10/preview.html","_blank",${fullscreen});
		[#else]
		window.open("/v/prototype10/preview","_blank",${fullscreen});
		[/#if]
	}
	,actionOnCommandExport:function(){
		//TODO:export on all pages
		var currentPage = this.selectedChildWidget;
		_previewer.set("title",agile.i18n("Export_Source",null,true) +" - " + currentPage.get("title"));		
		var prototype = currentPage.toHtml({cascade:true,indentCount:0,sourceType:"dojo"});		
		var template = '<textarea readonly style="font-family:Verdana;width:99%;height:96%">{code}</textarea><button style="position:absolute;float:left;left:50%;top:97%;" onclick="_previewer.hide()">{i18n_Close}</button>';
		var code = this.sourceTemplate.replace("</body>",prototype +"\n</body>");
		var content = lang.replace(template,{code:code,i18n_Close:agile.i18n("Close",null,true)});
		console.log(content);
		_previewer.set("content",content);
		
		_previewer.show();
		style.set(_previewer.domNode,{position:"absolute",left:"1px",top:"1px",width:"99%",height:"98%",backgroundColor:"white"});
		style.set(_previewer.containerNode,{width:"98%",height:"93%",overflow:"hidden"});
		style.set(_previewer.titleBar,{width:"99%"});
	}
	
//	,actionOnCommandExportPrototype:function(){
//		var currentPage = this.selectedChildWidget;
//		_previewer.set("title",agile.i18n("Export_Prototype",null,true) +" - " + currentPage.get("title"));		
//		var prototype = currentPage.toHtml(true,0,"agile");		
//		var template = '<center><textarea cols="180" rows="35" readonly style="font-family:Verdana">{code}</textarea><br/><button onclick="_previewer.hide()">{i18n_Close}</button></center>';
//		//var code = string.substitute(this.sourceTemplate,{body:prototype,theme:"claro",context:"${webAppHost}${context}"}).replace(/</g, "&lt;").replace(/>/g, "&gt;");
//		var code = lang.replace(this.sourceTemplate,{body:prototype,theme:"claro"}).replace(/</g, "&lt;").replace(/>/g, "&gt;");
//		_previewer.set("content",lang.replace(template,{code:code,i18n_Close:agile.i18n("Close",null,true)}));
//		//_previewer.set("content",lang.replace(this.sourceTemplate,{prototype:prototype}).replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\n/g, "<br>");		
//		_previewer.show();
//	}
	,actionOnCommandFeature:function(){
		_previewer.set("title",agile.i18n("Help",null,true));
//		agilePrototypeContent.set("href",agile.i18nUrl("feature.html"));
		_previewer.set("href",agile.i18nUrl("feature.html"));
		_previewer.show();
	}
//	,actionOnCommandSupport:function(){
//		_previewer.set("title",agile.i18n("Contact",null,true));		
//		_previewer.set("href",agile.i18nUrl("support.html"));
////		agilePrototypeContent.set("href",agile.i18nUrl("support.html"));
//		_previewer.show();
//	}
	,actionOnCommandRefresh:function(){			
		var currentPage = this.selectedChildWidget;					
		currentPage.refresh();
		topic.publish("agile.widget.selected",currentPage);
	}	
	,actionOnCommandDemo:function(){
		var child = this.createChild({title:agile.i18n("Demo",null,"Demo"),store:"sample"});	
		this.addChild(child);
		this.selectChild(child); 
	}
//	,onPageSelected:function(page){
//		if(!page) return;
//		//fetch content for the first time
//		if(!page.fetched){
//			page.refresh(true);
//		}
//[#--		
////		if(!page.editable){
////			style.set(this.removeButton,{display:"none"});
////		}
////		this.showControlButtons(page);
//--]		
////		console.error("onPageSelected@@@@@@@@@@",page.shortName,"-",page.get("title"));
//		topic.publish("agile.widget.selected",page);
//	}

[/@]